
//
//  YJcateClassController.m
//  SnackCourier
//
//  Created by qianfeng01 on 15/7/24.
//  Copyright (c) 2015年 qianfeng01. All rights reserved.
//

#import "YJcateClassController.h"

#import "YJcateclassModel.h"
#import "YJcateclassFollowModel.h"

#import "BaseHeaderFlowLayout.h"


#import "YJCollectionCell.h"
#import "YJCollectionView.h"

#import "YJSalesTopicListdetailsCell.h"
#import "YJFirstview.h"


#import "CreateSales.h"

#import "YJcateDetaViewController.h"

static BOOL onetouch;
static BOOL twotouch;
static BOOL theratouch;

@interface YJcateClassController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *classArray;
@property (nonatomic,strong) NSMutableArray *follwArray;
@property (nonatomic,strong) UIButton *classButton;

@property (nonatomic,strong) UIButton *one;
@property (nonatomic,strong) UIButton *two;
@property (nonatomic,strong) UIButton *thera;

@property (nonatomic,assign) NSInteger height;
@property (nonatomic,assign) NSInteger h_y;

@end

@implementation YJcateClassController

- (void)viewDidLoad {
    [super viewDidLoad];
    onetouch =YES;
    twotouch =NO;
    theratouch =NO;
    self.currentPage=0;
    self.dataArray =[[NSMutableArray alloc] init];
    self.classArray =[[NSMutableArray alloc] init];
    self.follwArray =[[NSMutableArray alloc] init];
    
    NSString *url1 =[[NSString alloc] initWithFormat:kClassificationUrl,(long)self.id];
    NSString *url2 =[[NSString alloc] initWithFormat:kClassflowerUrl,(long)self.id,kdefault,(long)self.currentPage];
    
    
    [self creatscrollView];
    [self createHttpRequest];
    [self createData:url1 classData:url2];
}

-(void)createData:(NSString *)url1 classData:(NSString *)url2{
    [self.dataArray removeAllObjects];
    [self.classArray removeAllObjects];
    [self.follwArray removeAllObjects];
    
    __weak typeof (self)weakSelf=self;
    [self.manager GET:url1 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            NSDictionary *dicts =[NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            NSArray *dataArray =dicts[@"data"];
            for (NSDictionary *dict in dataArray) {
                YJcateclassModel *model =[[YJcateclassModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [weakSelf.classArray addObject:model];
            }
            [weakSelf.dataArray addObject:weakSelf.classArray];
        }
         [weakSelf.collectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    [self.manager GET:url2 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            NSDictionary *dicts=[NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *data =dicts[@"data"];
            NSArray *productListArray =data[@"productList"];
            for (NSDictionary *dict in productListArray) {
                YJcateclassFollowModel *model =[[YJcateclassFollowModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [weakSelf.follwArray addObject:model];
            }
            [weakSelf.dataArray addObject:weakSelf.follwArray];
        }
        [weakSelf.collectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

-(void)creatscrollView{
    BaseHeaderFlowLayout *flowLayout =[[BaseHeaderFlowLayout alloc] init];
    flowLayout.scrollDirection =UICollectionViewScrollDirectionVertical;
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.collectionView =[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64-55)collectionViewLayout:flowLayout];
    self.collectionView.delegate =self;
    self.collectionView.dataSource =self;
    self.collectionView.backgroundColor =[UIColor colorWithWhite:0.8 alpha:1];
    
    [self.collectionView registerClass:[YJFirstview class] forCellWithReuseIdentifier:@"YJFirstview"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"YJSalesTopicListdetailsCell" bundle:nil] forCellWithReuseIdentifier:@"YJSalesTopicListdetailsCell"];
    
    
    [self.collectionView registerClass:[YJCollectionView class]forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YJCollectionView"];
    [self.collectionView registerClass:[YJCollectionCell class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YJCollectionCell"];
    [self.view addSubview:self.collectionView];
    
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataArray.count;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section ==0) {
        return 1;
    }else{
        return self.follwArray.count;
    }
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        YJFirstview *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"YJFirstview" forIndexPath:indexPath];
        return cell;
    }else{
        YJSalesTopicListdetailsCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"YJSalesTopicListdetailsCell" forIndexPath:indexPath];
        YJcateclassFollowModel *model =self.follwArray[indexPath.row];
        [cell showDataWithfollowModel:model];
        cell.backgroundColor =[UIColor whiteColor];
        return cell;
    }
    
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return CGSizeMake(0, 0.01);
    }else{
        return CGSizeMake((self.view.frame.size.width-10)/2.0, 250);
    }
}

-(UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        UICollectionReusableView *view =nil;
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            view=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YJCollectionCell" forIndexPath:indexPath];
            view.backgroundColor =[UIColor whiteColor];
            UIView* redView =[[UIView alloc] initWithFrame:CGRectMake(10, 5, 5, 20)];
            redView.backgroundColor =[UIColor redColor];
            redView.layer.masksToBounds =YES;
            redView.layer.cornerRadius =2;
            [view addSubview:redView];
            
            UILabel *title =[[UILabel alloc] initWithFrame:CGRectMake(redView.frame.size.width+20, 0, 200, 20)];
            title.text =@"这些东西很好吃";
            [view addSubview:title];
            
            CGFloat width =75;
            CGFloat height =30;
            NSInteger space =([UIScreen mainScreen].bounds.size.width-75*4)/5;
         
            NSInteger space_y =((_height- 40)-30 *_h_y)/(_h_y+1);
            for (int i =0; i<self.classArray.count; i++) {
                int x =i%4;
                int y=i/4;
                YJcateclassModel *model =self.classArray[i];
                UIButton *button =[UIButton buttonWithType:(UIButtonTypeSystem)];
                button.frame =CGRectMake(space*(x+1)+width*x,title.frame.size.height+title.frame.origin.y+5+space_y*(y+1)+height*y, width, height);
                [button setTitle:model.cateName forState:(UIControlStateNormal)];
                button.font =[UIFont systemFontOfSize:10];
                button.backgroundColor =[UIColor colorWithWhite:0.9 alpha:1];
                button.layer.masksToBounds =YES;
                button.layer.cornerRadius=5;
                button.tag =101+i;
                [button addTarget:self action:@selector(btnClick:) forControlEvents:(UIControlEventTouchUpInside)];
                [view addSubview:button];
                
            }
        }
        return view;
    }else{
        UICollectionReusableView *view =nil;
        view.backgroundColor=[UIColor whiteColor];
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            view =[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YJCollectionView" forIndexPath:indexPath];
            _one=[[UIButton alloc]initWithFrame:CGRectMake(0,2,self.view.frame.size.width/3.0,26)];
            _two=[[UIButton alloc]initWithFrame:CGRectMake(_one.frame.size.width,2,self.view.frame.size.width/3.0,26)];
            _thera=[[UIButton alloc]initWithFrame:CGRectMake(_two.frame.size.width*2,2,self.view.frame.size.width/3.0,26)];
            [_one addTarget:self action:@selector(clickbtn:) forControlEvents:UIControlEventTouchUpInside];
            [_two addTarget:self action:@selector(clickbtn:) forControlEvents:UIControlEventTouchUpInside];
            [_thera addTarget:self action:@selector(clickbtn:) forControlEvents:UIControlEventTouchUpInside];
            _one.tag=301;
            _two.tag =302;
            _thera.tag=303;
            if (onetouch==YES) {
                [_one setBackgroundImage:[UIImage imageNamed:@"zonghe"] forState:UIControlStateNormal];
            }else if(onetouch ==NO){
                [_one setBackgroundImage:[UIImage imageNamed:@"zonghe_1"] forState:UIControlStateNormal];
            }
            if (twotouch==YES){
                [_two setBackgroundImage:[UIImage imageNamed:@"rexiao"] forState:UIControlStateNormal];
            }else if(twotouch ==NO){
                [_two setBackgroundImage:[UIImage imageNamed:@"rexiao_1"] forState:UIControlStateNormal];
            }
            if (theratouch==YES){
                [_thera setBackgroundImage:[UIImage imageNamed:@"jiage"] forState:UIControlStateNormal];
            }else if (theratouch==NO){
                [_thera setBackgroundImage:[UIImage imageNamed:@"jiage_1"] forState:UIControlStateNormal];
            }
            [view addSubview:_one];
            [view addSubview:_two];
            [view addSubview:_thera];
            view.backgroundColor =[UIColor colorWithWhite:0.8 alpha:1];
        }
        return view;
    }
}

-(void)setClassButton:(UIButton *)classButton{
    if (_classButton ==classButton) {
        return;
    }
    _classButton.selected =NO;
    _classButton =classButton;
    _classButton.selected =YES;
}

-(void)clickbtn:(UIButton *)button {
    switch (button.tag) {
        case 301:
        {
            onetouch=YES;
            twotouch=NO;
            theratouch=NO;
            NSString *url1 =[NSString stringWithFormat:kClassificationUrl,(long)self.id];
            NSString *url2 =[NSString stringWithFormat:kClassflowerUrl,(long)self.id,kdefault,(long)self.currentPage];
            [self.dataArray removeAllObjects];
            [self.collectionView reloadData];
            [self createData:url1 classData:url2];
        }
            break;
        case 302:
        {
            onetouch=NO;
            twotouch=YES;
            theratouch=NO;
            NSString *url1 =[NSString stringWithFormat:kClassificationUrl,(long)self.id];
            NSString *url2 =[NSString stringWithFormat:kClassflowerUrl,(long)self.id,ksales,(long)self.currentPage];
            [self.dataArray removeAllObjects];
            [self.collectionView reloadData];
            [self createData:url1 classData:url2];
        }
            break;
        case 303:
        {
            onetouch=NO;
            twotouch=NO;
            theratouch=YES;
            NSString *url1 =[NSString stringWithFormat:kClassificationUrl,(long)self.id];
            NSString *url2 =[NSString stringWithFormat:kClassflowerUrl,(long)self.id,kprice,(long)self.currentPage];
            [self.dataArray removeAllObjects];
            [self.collectionView reloadData];
            [self createData:url1 classData:url2];
        }
            break;
            
        default:
            break;
    }
}

-(void)btnClick:(UIButton *)button{
    YJcateDetaViewController *controller =[[YJcateDetaViewController alloc] init];
    YJcateclassModel *model =self.classArray[button.tag -101];
    controller.classModel =model;
    [self.navigationController pushViewController:controller animated:YES];
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section ==0) {
        NSInteger y =self.classArray.count/4;
        NSInteger yy =self.classArray.count%4;
        if (yy>=1&&yy<=3) {
            _h_y=y+1;
        }else{
            _h_y=y;
        }
        _height=_h_y*35+40;
        return CGSizeMake(0, _height);
    }
    return CGSizeMake(0, 30);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        YJcateclassFollowModel *model =self.follwArray[indexPath.row];
        YJImmediatelygrabController *controller =[CreateSales createVC:model.id];
        controller.title =@"商品详情";
        [self.navigationController pushViewController:controller animated:YES];
    }
}

@end
